#include "math_3d.h"
#define GLEW_STATIC 1
#include <GL/glew.h>
#include <glut.h>
#include "glwindow.h"
#include "shader.hpp"
#include "config.h"
#include "Clock.h"
#include <glm/glm.hpp>

static GLuint vertexBufferId;
typedef struct vertice
{
	glm::vec3 position;
	glm::vec3 color;

};

static vertice tri1[] = {
	
	-1.0f, 1.0f,0.0f,
	1.0f, 0.0f,0.0f,

	-1.0f, 0.0f,0.0f,
	0.0f, 1.0f,0.0f,

	0.0f, 0.0f,0.0f,
	1.0f, 0.0f,0.0f,

};

static GLfloat tri2[] = {
	-1.0f, -1.0f,0.0f,
	1.0f, 0.0f,0.0f,

	-1.0f, 0.0f,0.0f,
	0.0f, 1.0f,0.0f,

	0.0f, 0.0f,0.0f,
	1.0f, 0.0f,0.0f,

};

static GLfloat tri3[] = {
	1.0f, -1.0f,0.0f,
	1.0f, 0.0f,0.0f,

	1.0f, 0.0f,0.0f,
	0.0f, 1.0f,0.0f,

	0.0f, 0.0f,0.0f,
	1.0f, 0.0f,0.0f,

};

static GLfloat tri4[] = {
	1.0f, 1.0f,0.0f,
	1.0f, 0.0f,0.0f,

	1.0f, 0.0f,0.0f,
	0.0f, 1.0f,0.0f,

	0.0f, 0.0f,0.0f,
	1.0f, 0.0f,0.0f,

};




static void OnInitScene(void)
{
	glGenBuffers(1,&vertexBufferId);
	glBindBuffer(GL_ARRAY_BUFFER,vertexBufferId);
	// Allocate memory
    glBufferData(GL_ARRAY_BUFFER,1000,NULL,GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(float)*6,0);
 
	
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,sizeof(float)*6,(char *)(sizeof(float)*3));

	
		
	GLuint program = LoadShaders("shaders\\basic.vs","shaders\\basic.fs");
	glUseProgram(program);

}

static void OnReshapeWindow(int width,int height)
{
	glViewport(0,0,width,height);
}
int show_triangle = 0;
int triangle_count = 1;
static void OnUpdateScene(float time)
{
	if(show_triangle)
	{
		if(triangle_count == 1)
			glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(tri1),tri1);
		if(triangle_count == 2)
			glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(tri1),tri2);
		if(triangle_count == 3)
			glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(tri1),tri3);
		if(triangle_count == 4)
			glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(tri1),tri4);

		triangle_count++;
		if(triangle_count > 4)
			triangle_count = 1;
		show_triangle = 0;
	}

	

//	printf("Update %f\n",time);
}

static void OnRenderScene(void)
{
	

	glClear(GL_COLOR_BUFFER_BIT);
	
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    glDrawArrays(GL_TRIANGLES,0,6);
	//glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_SHORT,0);
    glutSwapBuffers();
}

static void  KeyBoardHandler(unsigned char key,int x,int y)
{
	if(key == 97)
		show_triangle = 1;

}
void UsingGlm(int argc, char **argv)
{
	printf("Running UsingGlm\n");
	// Press a to show triangle
	// Also show how glClear(GL_COLOR_BUFFER_BIT) clears the buffer else old contents remains on screen
	GLWindowCreate(1024,1024);

	SetInitSceneCallBack(OnInitScene);
	SetReshapeWindowCallBack(OnReshapeWindow);
	SetUpdateSceneCallBack(OnUpdateScene);
	SetRenderSceneCallBack(OnRenderScene);
	SetUpKeyboardCallBack(KeyBoardHandler);
	GLWindowStart();
}


